package com.SpringbootVue.controller;

import com.SpringbootVue.pojo.Article;
import com.SpringbootVue.pojo.PageBean;
import com.SpringbootVue.pojo.Result;
import com.SpringbootVue.service.ArticleService;
import com.SpringbootVue.utils.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success();
    }

    @GetMapping
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ) {
        PageBean<Article> pb = articleService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pb);
    }

    //测试接口，当没有拦截器也没有做登录token验证时，即使没有登录时也能直接访问这个接口方法并能获取数据
    @GetMapping("/listTest")
    public Result<String> listTest() {
        return Result.success("所有的文章数据..");
    }
    //测试接口，使用JWT令牌验证，要在该方法里显示的获取请求头的令牌token，
    // 并写逻辑，如果获取请求头的token和登录的token一样则能获取数据，否则令牌对应不上，未登录，返回401错误信息
    @GetMapping("/listJWT")
    public Result<String> listJWT(@RequestHeader(name = "Authorization") String token,
                                  HttpServletResponse response) {
       //这里的token验证以及@RequestHeader(name = "Authorization") String token可以直接放在拦截器实现
        try {        //验证token
            Map<String, Object> claims = JwtUtil.parseToken(token);
            System.out.println(claims.get("user"));
            return Result.success("所有的文章数据...");
        } catch (Exception e) {
            //如果没有登录，http响应状态码为401
            response.setStatus(401);
            return Result.error("未登录");
        }
    }
}
